<template>
  <BaseDialog
    :visible="visible"
    :title="dialogTitle"
    width="80%"
    draggable
    @update:visible="handleUpdateVisible"
    @close="handleClose"
    @closed="handleClosed"
  >
    <div class="record-dialog-content">
      <!-- 查询条件 -->
      <div class="query-panel mb-4">
        <el-form :model="queryForm" inline class="query-form">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="queryForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="queryForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
            />
          </el-form-item>
          <el-form-item label="录像类型">
            <el-select v-model="queryForm.recordType" placeholder="选择类型" size="small" style="width: 120px">
              <el-option label="全部" value="all" />
              <el-option label="计划录像" value="schedule" />
              <el-option label="手动录像" value="manual" />
              <el-option label="告警录像" value="alarm" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button size="small" @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 录像记录列表 -->
      <div class="record-table">
        <ElementTable
          :table-title="tableColumns"
          :show-pagination="true"
          :page-config="pageConfig"
          :max-height="500"
          :data="recordList"
        >
          <!-- 时长自定义插槽 -->
          <template #duration="{ data }">
            <span>{{ formatDuration(data.row.duration) }}</span>
          </template>
          
          <!-- 文件大小自定义插槽 -->
          <template #fileSize="{ data }">
            <span>{{ formatFileSize(data.row.fileSize) }}</span>
          </template>
          
          <!-- 操作按钮插槽 -->
          <template #actions="{ data }">
            <el-button size="small" text @click="handlePlay(data.row)">
              <el-icon><VideoPlay /></el-icon>
              播放
            </el-button>
            <el-button size="small" text @click="handleDownload(data.row)">
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </template>
        </ElementTable>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import BaseDialog from '@/components/BaseDialog.vue'
import ElementTable from '@/components/ElementTable/index.vue'
import { Search, Refresh, VideoPlay, Download } from '@element-plus/icons-vue'
import { usePlaybackStore } from '@/stores/playback'
// 工具函数
const formatDuration = (seconds: number): string => {
  const hrs = Math.floor(seconds / 3600)
  const mins = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hrs > 0) {
    return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

interface Props {
  visible: boolean
  camera?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'play', record: any): void
  (e: 'download', record: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const playbackStore = usePlaybackStore()

// 查询表单
const queryForm = ref({
  startTime: '',
  endTime: '',
  recordType: 'all'
})

// 弹框标题
const dialogTitle = computed(() => {
  return props.camera ? `录像记录 - ${props.camera.name}` : '录像记录'
})

// 表格列配置
const tableColumns = [
  { prop: 'startTime', label: '开始时间', width: 180 },
  { prop: 'endTime', label: '结束时间', width: 180 },
  { prop: 'duration', label: '时长', width: 100, slot: 'duration' },
  { prop: 'fileSize', label: '文件大小', width: 120, slot: 'fileSize' },
  { prop: 'quality', label: '画质', width: 80 },
  { prop: 'actions', label: '操作', width: 150, slot: 'actions' }
]

// 分页配置
const pageConfig = computed(() => ({
  currentPage: playbackStore.pagination.currentPage,
  pageSize: playbackStore.pagination.pageSize,
  total: playbackStore.pagination.total,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 录像记录列表
const recordList = computed(() => playbackStore.recordList)

// 处理弹框显示状态
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 关闭弹框
const handleClose = () => {
  emit('update:visible', false)
}

// 弹框关闭后
const handleClosed = () => {
  // 可以在这里做一些清理工作
}

// 查询录像记录
const handleSearch = () => {
  if (props.camera) {
    // 使用 store 中的方法加载录像记录
    playbackStore.loadCameraRecords(props.camera.id.toString())
  }
}

// 重置查询条件
const handleReset = () => {
  queryForm.value = {
    startTime: '',
    endTime: '',
    recordType: 'all'
  }
  handleSearch()
}

// 播放录像
const handlePlay = (record: any) => {
  emit('play', record)
}

// 下载录像
const handleDownload = (record: any) => {
  emit('download', record)
}

// 监听摄像头变化，自动加载录像记录
watch(() => props.camera, (newCamera) => {
  if (newCamera && props.visible) {
    handleSearch()
  }
}, { immediate: true })

// 监听弹框显示状态
watch(() => props.visible, (visible) => {
  if (visible && props.camera) {
    handleSearch()
  }
})
</script>

<style scoped lang="scss">
.record-dialog-content {
  .query-panel {
    border-bottom: 1px solid #e5e7eb;
    padding-bottom: 16px;
    
    .query-form {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
    }
  }
  
  .record-table {
    margin-top: 16px;
  }
}
</style>
